﻿
#include "LinkManager.h"

#include <memory>
#include <QSharedPointer>
#include <QDebug>

LinkManager::LinkManager(QObject *parent)
    : QObject{parent}
{

}

SerialLink* LinkManager::createSerialLink(const QString & port_name,
                                          int baud,int data_bits,
                                          int stop_bits,int parity)
{
    auto link = new SerialLink(port_name,baud,data_bits,stop_bits,parity,this);
    link->type(LinkInterface::Serial);
    return link;
}

ModbusRtuLink* LinkManager::creatModbusRtuLink(const QString & port_name,
                                              int baud,int data_bits,
                                              int stop_bits,int parity)
{
    auto link = new ModbusRtuLink(port_name,baud,data_bits,stop_bits,parity,this);
    link->type(LinkInterface::Modbus);
    return link;
}

QStringList LinkManager::serialPorts  ()
{
    if(!serialPortList_.size()){
        updateSerialPorts();
    }
    return serialPortList_;
}

QString LinkManager::cleanPortDisplayname_(const QString &name)
{
    QString pname = name.trimmed();
#ifdef Q_OS_WIN
    pname.replace("\\\\.\\", "");
#else
    pname.replace("/dev/cu.", "");
    pname.replace("/dev/", "");
#endif
    return pname;
}

void LinkManager::updateSerialPorts()
{
    serialPortList_.clear();
    QList<QSerialPortInfo> portList = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo &info: portList){
        QString port = info.systemLocation().trimmed();
        serialPortList_ += cleanPortDisplayname_(port);
    }
    emit serialPortsChanged();
}

